<script>
	import {
		connectWS,
		closeWS,
		initNetworkListener,
		getWSStatus,
		forceReconnect,
		testWebSocketConnection
	} from '@/utils/webSokent.js';
	import {
		getUserInfo,
		notificationList
	} from "@/api/members.js"
	import storage from "@/utils/storage.js";
	import modalManager, {
		MODAL_KEYS
	} from "@/utils/modalManager.js";
	import performanceMonitor from "@/utils/performanceMonitor.js";
	import {
		errorHandler
	} from "@/utils/errorHandler.js";
	import simpleTimerCleaner from "@/utils/simpleTimerCleaner.js";


	export default {
		data() {
			return {
				userInfo: {}
			}
		},
		onLaunch() {
			// 初始化错误处理
			errorHandler.init();
			// 启动性能监控
			performanceMonitor.startMonitoring();
			// 初始化网络监听
			initNetworkListener();
			this.initWebSocket();

			// 启动简单定时器清理监控
			this.startSimpleTimerCleanup();

			// 暂时禁用路由栈监控，避免导入错误

		},

		onHide() {
			// 应用隐藏时不关闭WebSocket，保持连接
			// closeWS();
		},

		onShow() {
			// 应用显示时检查并重新连接WebSocket
			this.initWebSocket();
			// 重置会话期间的弹窗状态，允许新的弹窗
			modalManager.resetSessionModals();
		},

		// 监听页面显示事件，用于处理reLaunch后的WebSocket重连
		onPageShow() {
			// 页面显示时检查WebSocket连接状态
			setTimeout(() => {
				this.checkAndReconnectWebSocket();
			}, 1000);
		},

		onUnload() {
			// 应用卸载时关闭WebSocket
			closeWS();
			// 停止性能监控
			performanceMonitor.stopMonitoring();
			// 暂时禁用路由栈监控，避免导入错误

			// 清理所有定时器
			simpleTimerCleaner.clearAllTimers();
		},

		methods: {
			// 启动简单定时器清理监控
			startSimpleTimerCleanup() {
				// 每20秒检查一次定时器状态
				setInterval(() => {
					const stats = simpleTimerCleaner.getStats();
					if (stats.totalTimers > 15) {
						console.warn(`[App] 检测到过多定时器: ${stats.totalTimers}，执行清理`);
						simpleTimerCleaner.clearAllTimers();
					}
				}, 20000);
			},

			// 初始化WebSocket连接
			initWebSocket() {
				const token = storage.getAccessToken();
				if (token) {
					// 检查当前连接状态
					const status = getWSStatus();

					// 如果连接异常，强制重连
					if (status.isConnected && status.lastHeartbeatTime > 0) {
						const timeSinceLastHeartbeat = Date.now() - status.lastHeartbeatTime;
						if (timeSinceLastHeartbeat > 60000) { // 超过1分钟没有心跳
							forceReconnect();
							return;
						}
					}

					// 如果已经连接且状态正常，不需要重新连接
					if (status.isConnected && status.readyState === 1) {
						return;
					}

					connectWS(token, (msg) => {
						this.handleWebSocketMessage(msg);
					});
				}
			},

			// 检查并重连WebSocket（用于reLaunch后的恢复）
			checkAndReconnectWebSocket() {
				const token = storage.getAccessToken();
				if (token) {
					const status = getWSStatus();

					// 如果WebSocket未连接或连接异常，尝试重连
					if (!status.isConnected || status.readyState !== 1) {
						forceReconnect();
					}
				}
			},

			// 调试WebSocket连接（开发环境使用）
			debugWebSocket() {
				testWebSocketConnection();
			},

			handleWebSocketMessage(msg) {
				switch (msg.type) {
					case 'unreadCount':
						this.$store.commit('SETCOUNT', msg.data?.count ?? msg.count);
						break;
					case 'user_auth_result':
						this.handleAuthResult(msg.data);
						break;
					case 'notify':
						this.handleNotification(msg.data || msg.info || msg);
						break;
					case 'work_order_progress':
						this.handleworkOrderMessage(msg.data || msg.info || msg);
						break;
					case 'chat':
						this.$store.commit('setChatId', msg.data?.from ?? msg.from);
						break;
					case 'chatUnreadCount':
						this.$store.commit('setChatUnreadCount', msg.data?.count ?? msg.count);
						break;
					case 'repair_order':
						// 服务订单通知处理
						break;
					case 'newOrder':
						this.handleNewOrder(msg.data);
						break;
						// 商品订单状态更新通知
					case 'product_order_delivered':
						this.handleProductOrderDelivered(msg.data);
						break;
						// 提现相关通知
					case 'withdraw_approved':
						this.handleWithdrawApproved(msg.data);
						break;
					case 'withdraw_rejected':
						this.handleWithdrawRejected(msg.data);
						break;
					case 'withdraw_transfer_initiated':
						// this.handleWithdrawTransferInitiated(msg.data);
						break;
					case 'withdraw_success':
						this.handleWithdrawSuccess(msg.data);
						break;
					case 'withdraw_failed':
						this.handleWithdrawFailed(msg.data);
						break;
					case 'withdraw_unconfirmed_reminder':
						this.handleWithdrawUnconfirmedReminder(msg.data);
						break;
					default:
						// 未知消息类型，静默处理
						break;
				}
			},
			// 处理业主认证结果
			handleAuthResult(data) {
				if (data.result === 'approved') {
					uni.showToast({
						title: '业主认证审核通过！',
						icon: 'success',
						duration: 3000
					});
					// 认证通过后，延迟一下再刷新用户信息，确保后端数据已更新
					setTimeout(() => {
						this.refreshUserInfo();
					}, 500);
				} else if (data.result === 'rejected') {
					uni.showModal({
						title: '认证未通过',
						content: data.message || '很抱歉，您的业主认证审核未通过',
						showCancel: false,
						confirmText: '我知道了'
					});
					// 认证被拒绝也需要刷新用户信息
					this.refreshUserInfo();
				}
			},
			handleworkOrderMessage(info) {
				uni.showModal({
					title: info.title || '工单进度',
					content: info.content,
					showCancel: false
				});
			},
			handleNotification(info) {
				if (info.type === 'post_audit_result') {
					if (info.data.result === 'approved') {
						uni.showToast({
							title: '帖子审核通过',
							icon: 'success'
						});
					} else {
						uni.showModal({
							title: '帖子审核未通过',
							content: info.data.message,
							showCancel: false
						});
					}
				} else {
					uni.showToast({
						title: info.content || '收到新通知',
						icon: 'none'
					});
				}
			},
			// 处理新订单消息
			handleNewOrder(data) {
				const {
					orderNo,
					totalAmount,
					shopName
				} = data;
				uni.showModal({
					title: '新订单通知',
					content: `您有新的订单！\n订单号：${orderNo}\n金额：¥${totalAmount}\n店铺：${shopName}`,
					showCancel: false,
					confirmText: '查看订单',
					success: (res) => {
						if (res.confirm) {
							// 跳转到订单页面，您可以根据实际路由调整
							this.$router.smartNavigate({
								url: '/pages/mePages/shopCenter/index'
							});
						}
					}
				});
			},

			// 处理商品订单送达通知
			handleProductOrderDelivered(data) {
				const {
					orderNo,
					orderId,
					productName,
					deliveryTime,
					shopName
				} = data;

				uni.showModal({
					title: '商品订单已送达',
					content: `您的商品订单已送达！\n订单号：${orderNo}`,
					showCancel: false,
					confirmText: '查看订单',
					success: (res) => {
						if (res.confirm) {
							// 跳转到订单中心页面
							this.$router.smartNavigate({
								url: '/pages/mePages/samOrder'
							});
						}
					}
				});
			},

			// 提现审核通过通知
			handleWithdrawApproved(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_APPROVED, 'session')) {
					return;
				}

				const {
					withdrawId,
					amount
				} = data;
				uni.showModal({
					title: '提现审核通过',
					content: `您的提现申请（${withdrawId}）已审核通过，金额：${amount}元，正在处理转账`,
					showCancel: false,
					confirmText: '查看详情',
					success: (res) => {
						if (res.confirm) {
							// 可以跳转到提现记录页面
							this.$router.smartNavigate({
								url: '/pages/mePages/balance/WithdrawRecords'
							});
						}
					}
				});
			},

			// 提现审核拒绝通知
			handleWithdrawRejected(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_REJECTED, 'session')) {
					return;
				}

				const {
					withdrawId,
					amount,
					reason
				} = data;
				uni.showModal({
					title: '提现审核未通过',
					content: `您的提现申请（${withdrawId}）被拒绝，原因：${reason}`,
					showCancel: false,
					confirmText: '查看详情',
					success: (res) => {
						if (res.confirm) {
							// 可以跳转到提现记录页面
							this.$router.smartNavigate({
								url: '/pages/mePages/balance/WithdrawRecords'
							});
						}
					}
				});
			},

			// 转账发起通知
			handleWithdrawTransferInitiated(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_TRANSFER_INITIATED, 'session')) {
					return;
				}

				const {
					withdrawId,
					amount,
					transferBillNo
				} = data;
				uni.showModal({
					title: '转账已发起',
					content: `您的提现申请（${withdrawId}）转账已发起，金额：${amount}元，请及时确认收款`,
					showCancel: false,
					confirmText: '去确认',
					success: (res) => {
						if (res.confirm) {
							// 跳转到提现记录页面
							this.$router.smartNavigate({
								url: '/pages/mePages/balance/WithdrawRecords'
							});
							// 跳转到确认收款页面
							// this.showConfirmReceiptModal(data);
						}
					}
				});
			},

			// 提现成功通知
			handleWithdrawSuccess(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_SUCCESS, 'session')) {
					return;
				}

				const {
					withdrawId,
					amount
				} = data;
				uni.showToast({
					title: `提现成功！金额：${amount}元`,
					icon: 'success',
					duration: 3000
				});
			},

			// 提现失败通知
			handleWithdrawFailed(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_FAILED, 'session')) {
					return;
				}

				const {
					withdrawId,
					amount,
					reason
				} = data;
				uni.showModal({
					title: '提现失败',
					content: `您的提现申请（${withdrawId}）处理失败，原因：${reason}`,
					showCancel: false,
					confirmText: '我知道了'
				});
			},

			// 未确认收款提醒
			handleWithdrawUnconfirmedReminder(data) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_UNCONFIRMED_REMINDER, 'session')) {
					return;
				}

				const {
					count,
					withdrawals
				} = data;
				uni.showModal({
					title: '未确认收款提醒',
					content: `您有 ${count} 笔提现转账等待确认收款，请及时确认`,
					showCancel: false,
					confirmText: '去确认',
					success: (res) => {
						if (res.confirm) {
							// 跳转到提现记录页面
							this.$router.smartNavigate({
								url: '/pages/mePages/balance/WithdrawRecords'
							});
							// 显示确认收款弹窗
							// this.showBatchConfirmReceiptModal(withdrawals);
						}
					}
				});
			},

			// 显示确认收款弹窗
			showConfirmReceiptModal(withdrawData) {
				const {
					withdrawId,
					amount,
					transferBillNo
				} = withdrawData;
				uni.showModal({
					title: '确认收款',
					content: `请确认您已收到转账金额：${amount}元\n转账单号：${transferBillNo}`,
					confirmText: '已收到',
					cancelText: '未收到',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用确认收款API
								const {
									confirmWithdrawReceipt
								} = await import('@/api/withdraw.js');
								const response = await confirmWithdrawReceipt(withdrawId);

								if (response.success) {
									uni.showToast({
										title: '确认收款成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: response.message || '确认收款失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('确认收款失败:', error);
								uni.showToast({
									title: '确认收款失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 显示批量确认收款弹窗
			async showBatchConfirmReceiptModal(withdrawals) {
				const totalAmount = withdrawals.reduce((sum, item) => sum + parseFloat(item.amount), 0);

				const modalResult = await new Promise((resolve) => {
					uni.showModal({
						title: '未确认收款提醒',
						content: `您有 ${withdrawals.length} 笔提现转账等待确认，总金额：${totalAmount.toFixed(2)}元\n请前往提现记录页面进行确认`,
						confirmText: '去确认',
						cancelText: '稍后确认',
						success: (res) => {
							resolve(res.confirm);
						}
					});
				});

				if (modalResult) {
					// 跳转到提现记录页面
					this.$router.smartNavigate({
						url: '/pages/mePages/balance/WithdrawRecords'
					});
				}
			},

			// 刷新用户信息
			async refreshUserInfo() {
				try {
					const response = await getUserInfo();
					if (response.data.code === 200) {
						this.userInfo = response.data.data;
						storage.setUserInfo(response.data.data);
						// 更新store中的用户信息
						this.$store.commit('SETUSERINFO', response.data.data);
					}
				} catch (error) {
					console.error('刷新用户信息失败:', error);
				}
			}
		}
	}
</script>

<style lang="scss">
	//colorui
	@import "@/static/colorui/main.css";
	@import "@/static/colorui/icon.css";
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	/* #ifndef APP-NVUE */
	@import '@/static/customicons.css';

	/* #endif */
	// 设置整个项目的背景色
	page {
		height: 100vh;
		background-color: #f5f5f5;
	}

	image {
		width: 100%;
		height: 100%;
		display: block;
		vertical-align: middle;
	}

	.navBar {
		width: 100%;
		padding: 0 20px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.cu-bar.tabbar {
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding-bottom: calc(env(safe-area-inset-bottom));
	}
</style>